package com.bandit.factory;

import java.lang.reflect.InvocationTargetException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 获取单例对象的工厂
 * @author Bandit
 * @create 2022/2/23 10:21
 */
public class SingletonFactory {
    private static final Map<String,Object>  OBJECT_MAP = new ConcurrentHashMap<>();

    private SingletonFactory(){

    }

    public static <T> T getInstance(Class<T> c){
        if(c == null) {
            throw new IllegalArgumentException();
        }
        //名字作为key
        String key = c.toString();
        if(OBJECT_MAP.containsKey(key)){//如果有key就转换为该类型
            return c.cast(OBJECT_MAP.get(key));
        } else {
            return c.cast(OBJECT_MAP.computeIfAbsent(key,k->{
                try {
                    //反射获取单例对象
                    return c.getDeclaredConstructor().newInstance();
                } catch (InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
                    throw new RuntimeException(e.getMessage(),e);
                }
            }));
        }
    }
}
